package com.wise.site.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.json.JSONObject;

import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.wise.site.R;
import com.wise.site.detail.DetailShareActivity;
import com.wise.site.main.LoginActivity;
import com.wise.site.more.WeiboSettingActivity;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

public class SinaWeiboUtil {
	private static final String KEY = "3574376276";
	private static final String SECRET = "0bcf3966be265f5d1aa542e2ac7d693f";
	private static final String URL = "http://www.google.com.hk";
	
	

	public static void callAuthorizeUI(Activity activity){
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(KEY, SECRET);
		weibo.setRedirectUrl(URL);
		weibo.authorize(activity, new AuthDialogListener(activity));
	}
	
	
	
	public static String getAuthorizeUserName(Context context){
		String userName = null;
		DBOpenHelper dbOpenHelper = new DBOpenHelper(context);
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		Cursor cursor = db.query("oauthKey", new String[]{"weibotype", "userName", "token", "openId", "clientId"}, "weibotype = ?", new String[]{"sina"}, null, null, null);
		if(cursor.moveToNext()){
			userName = cursor.getString(cursor.getColumnIndex("userName"));
		}
		cursor.close();
		db.close();
		dbOpenHelper.close();
		return userName;
	}
	
	public static boolean authorize(Context context, String userName, String token, String openId, String clientId){
		boolean isSuccess = false;
		try {
			logOut(context);
			DBOpenHelper dbOpenHelper = new DBOpenHelper(context);
			SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
			db.execSQL("insert into oauthKey(weibotype, userName, token, openId, clientId) values(?, ?, ?, ?, ?)", new Object[]{"sina", userName, token, openId, clientId});
			db.close();
			dbOpenHelper.close();
			
			/*SharedPreferences userInfo = context.getSharedPreferences("user_info", Activity.MODE_WORLD_WRITEABLE);
			SharedPreferences.Editor editor = userInfo.edit();
			editor.putString("token", token);
			editor.putString("openId", openId);
			editor.putString("clientId", clientId);
			editor.commit();*/
			
			isSuccess = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return isSuccess;
	}
	
	
	public static int sendSinaWeibo(Activity context, String content){
		int state = -1;
		Weibo weibo = Weibo.getInstance();
		DBOpenHelper dbOpenHelper = new DBOpenHelper(context);
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.query("oauthKey", new String[]{"token", "openId", "clientId"}, "weibotype = ?", new String[]{"sina"}, null, null, null);
		if(cursor.moveToNext()){
			String token = cursor.getString(cursor.getColumnIndex("token"));
			String openId = cursor.getString(cursor.getColumnIndex("openId"));
			String clientId = cursor.getString(cursor.getColumnIndex("clientId"));
			AccessToken accessToken = new AccessToken(token, SECRET);
			accessToken.setExpiresIn(clientId);
			weibo.setAccessToken(accessToken);
			weibo.setupConsumerConfig(KEY, SECRET);
			weibo.setRedirectUrl(URL);
			try {
				boolean flag = weibo.share2weibo(context, weibo.getAccessToken().getToken(), weibo.getAccessToken().getSecret(), content, null);
				state = 0;
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}
		cursor.close();
		db.close();
		dbOpenHelper.close();
		return state;
	}
	
	public static boolean logOut(Context context){
		boolean falg = false;
		try {
			DBOpenHelper dbOpenHelper = new DBOpenHelper(context);
			SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
			db.execSQL("delete from oauthKey where weibotype = ?", new String[]{"sina"});
			db.close();
			dbOpenHelper.close();
			falg = true;
		} catch (Exception e) {
		}
		return falg;
	}
	
	
	
	private static class AuthDialogListener implements WeiboDialogListener {
		private Context mContext;
		public AuthDialogListener(Context context){
			this.mContext = context;
		}
		

		@Override
		public void onComplete(Bundle values) {
			final String uid = values.getString("uid");
			final String token = values.getString("access_token");
			final String expires_in = values.getString("expires_in");
			AccessToken accessToken = new AccessToken(token, SECRET);
			accessToken.setExpiresIn(expires_in);
			Weibo weibo = Weibo.getInstance();
			weibo.setAccessToken(accessToken);
			
			new Thread(){
				public void run() {
					String userName = getUserName(mContext, uid, token);
					if(authorize(mContext, userName, token, SECRET, expires_in)){
						if(mContext instanceof DetailShareActivity){
							((DetailShareActivity)mContext).reSendSianWeibo();
						}else if(mContext instanceof WeiboSettingActivity){
							((WeiboSettingActivity)mContext).refreshSinaWeiboData();
						}else if(mContext instanceof LoginActivity){
							((LoginActivity)mContext).refreshSinaWeiboLoginState();
						}
					}
				};
			}.start();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			// TODO Auto-generated method stub
			Toast.makeText(mContext, R.string.logo_weibo_exception, Toast.LENGTH_SHORT).show();
			if(mContext instanceof WeiboSettingActivity){
				((WeiboSettingActivity)mContext).refreshSinaWeiboData();
			}else if(mContext instanceof LoginActivity){
				((LoginActivity)mContext).refreshSinaWeiboLoginState();
			}
		}

		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
			Toast.makeText(mContext, R.string.logo_weibo_error, Toast.LENGTH_SHORT).show();
			if(mContext instanceof WeiboSettingActivity){
				((WeiboSettingActivity)mContext).refreshSinaWeiboData();
			}else if(mContext instanceof LoginActivity){
				((LoginActivity)mContext).refreshSinaWeiboLoginState();
			}
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			if(mContext instanceof WeiboSettingActivity){
				((WeiboSettingActivity)mContext).refreshSinaWeiboData();
			}else if(mContext instanceof LoginActivity){
				((LoginActivity)mContext).refreshSinaWeiboLoginState();
			}
		}
		
	}
	
	
	private static String getUserName(Context context, String uid, String token){
		String urlStr = "https://api.weibo.com/2/users/show.json?uid=" + uid + "&access_token=" + token;
		String userName = context.getString(R.string.sina_weibo_text);
		try{
			java.net.URL url = new java.net.URL(urlStr);
			HttpURLConnection http = null;
			if (url.getProtocol().toLowerCase().equals("https"))
			{
			    trustAllHosts();
			    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
			    https.setHostnameVerifier(new HostnameVerifier() {
					
					@Override
					public boolean verify(String hostname, SSLSession session) {
						// TODO Auto-generated method stub
						return true;
					}
				});
			    http = https;
			}
			else
			{
			    http = (HttpURLConnection) url.openConnection();
			}
			InputStreamReader isr = new InputStreamReader(http.getInputStream(), "utf-8");
			BufferedReader br = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			br.close();
			isr.close();
			
			JSONObject obj = new JSONObject(sb.toString());
			userName = obj.getString("screen_name");
		} catch(Exception e){
			e.printStackTrace();
		}
		return userName;
	}
		
		private static void trustAllHosts()
		{
		    // Create a trust manager that does not validate certificate chains
		    TrustManager[] trustAllCerts = new TrustManager[]
		    { 
		        new X509TrustManager()
		        {
		             public java.security.cert.X509Certificate[] getAcceptedIssuers()
		             {
		                  return new java.security.cert.X509Certificate[] {};
		             }

		             public void checkClientTrusted(X509Certificate[] chain,String authType)throws CertificateException
		             {
		             }

		             public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException
		            {
		            }
		        }
		    };

		    //Install the all-trusting trust manager
		    try
		    {
		         SSLContext sc = SSLContext.getInstance("TLS");
		         sc.init(null, trustAllCerts, new java.security.SecureRandom());
		         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		    }
		    catch (Exception e)
		    {
		        e.printStackTrace();
		    }
		}
	
}
